<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

//------------------------
// 用户控制器
//-------------------------

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Exception;
use think\Loader;
use think\Config;
use think\Db;
use think\Request;

set_time_limit(0);

class Deposit extends Controller
{
    use \app\admin\traits\controller\Controller;

//    protected static $blacklist = ['delete', 'clear', 'deleteforever', 'recyclebin', 'recycle'];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        $map = array();

        if ($data['realname']) {
            $map['au.realname'] = array('like', "%{$data['realname']}%");
        }

        if ($data['collection_item']) {
            $map['dd.collection_item'] = array('=', "{$data['collection_item']}");
        }

        if ($data['collection_means']) {
            $map['dd.collection_means'] = array('=', "{$data['collection_means']}");
        }

        if ($data['collection_time']) {
            $map['dd.collection_time'] = array("between", [strtotime($data['collection_time'] . " 00:00:00"), strtotime($data['collection_time'] . " 23:59:59")]);
        }

        if ($data['refund_item']) {
            $map['dd.refund_item'] = array('=', "{$data['refund_item']}");
        }

        if ($data['refund_means']) {
            $map['dd.refund_means'] = array('=', "{$data['refund_means']}");
        }

        if ($data['refund_status']) {
            if($data['refund_status']==5)
                $data['refund_status'] = 0;
            $map['dd.refund_status'] = array('=', "{$data['refund_status']}");
        }

        if ($data['refund_time']) {
            $map['dd.refund_time'] = array("between", [strtotime($data['refund_time'] . " 00:00:00"), strtotime($data['refund_time'] . " 23:59:59")]);
        }

        if ($data['driver_name'] === '新手') {
            $map['d.driver_rank_id'] = ['=', 0];
        } elseif ($data['driver_name'] === '初级' || $data['driver_name'] === '中级' || $data['driver_name'] === '高级') {
            $map['dr.name'] = array('=', "{$data['driver_name']}");
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('driver_deposit')
            ->alias('dd')
            ->join('tp_admin_user au', 'dd.driver_id=au.id', 'left')
            ->join('tp_driver d', 'dd.driver_id=d.user_id', 'left')
            ->join('tp_driver_rank dr', 'd.driver_rank_id=dr.id', 'left')
            ->where($map)
            ->order('id desc')
            ->field('dd.*,au.realname,d.driver_rank_id,dr.name,au.id as driver_user_id')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

//        halt($list);
        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign('searchCondition', $data);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());

        return $this->view->fetch();
    }

    /**
     * 司机审核
     * @return mixed
     */
    public function driver_confirm()
    {
        $data = input();
        $map = array();

        if ($data['realname']) {
            $map['au.realname'] = array('like', "%{$data['realname']}%");
        }

        if ($data['collection_item']) {
            $map['dd.collection_item'] = array('=', "{$data['collection_item']}");
        }

        if ($data['collection_means']) {
            $map['dd.collection_means'] = array('=', "{$data['collection_means']}");
        }

        if ($data['collection_time']) {
            $map['dd.collection_time'] = array("between", [strtotime($data['collection_time'] . " 00:00:00"), strtotime($data['collection_time'] . " 23:59:59")]);
        }

        if ($data['refund_item']) {
            $map['dd.refund_item'] = array('=', "{$data['refund_item']}");
        }

        if ($data['refund_means']) {
            $map['dd.refund_means'] = array('=', "{$data['refund_means']}");
        }

        if ($data['refund_status']) {
            if($data['refund_status']==3)
                $data['refund_status'] = 0;
            $map['dd.refund_status'] = array('=', "{$data['refund_status']}");
        }

        if ($data['refund_time']) {
            $map['dd.refund_time'] = array("between", [strtotime($data['refund_time'] . " 00:00:00"), strtotime($data['refund_time'] . " 23:59:59")]);
        }

        if ($data['driver_name'] === '新手') {
            $map['d.driver_rank_id'] = ['=', 0];
        } elseif ($data['driver_name'] === '初级' || $data['driver_name'] === '中级' || $data['driver_name'] === '高级') {
            $map['dr.name'] = array('=', "{$data['driver_name']}");
        }

        $map['dd.refund_status'] = 4;

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('driver_deposit')
            ->alias('dd')
            ->join('tp_admin_user au', 'dd.driver_id=au.id', 'left')
            ->join('tp_driver d', 'dd.driver_id=d.user_id', 'left')
            ->join('tp_driver_rank dr', 'd.driver_rank_id=dr.id', 'left')
            ->where($map)
            ->order('id desc')
            ->field('dd.*,au.realname,d.driver_rank_id,dr.name,au.id as driver_user_id')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign('searchCondition', $data);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign("is_driver", 1);
        $this->view->assign('numPerPage', $list->listRows());

        return $this->view->fetch();
    }

    /**
     * 确认审核
     * @return mixed
     */
    public function check_confirm(){
        $data = input();

        if(!$data['id']){
            return ajax_return_error('缺少参数');
        }

        $info = Db::name('driver_deposit')->where('id',$data['id'])->find();

        if(!$info){
            return ajax_return_error('信息不存在');
        }

        if($info['refund_status'] != 4){
            return ajax_return_error('该状态下不可进行确认审核操作或已确认');
        }

        $res = Db::name('driver_deposit')->where('id',$data['id'])->update(['refund_status'=>3]);

        if($res){
            return ajax_return_error('操作成功');
        }else{
            return ajax_return_error('操作失败');
        }
    }

    /**
     * 电子表格
     * @return mixed
     */

    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['id', '司机', '收款项目', '收款押金金额', '收款方式', '收款押金时间', '退款项目', '退还押金金额', '退款方式', '退还押金时间', '退款状态', '备注','司机等级'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }
        $map = array();

        if ($data['realname']) {
            $map['au.realname'] = array('like', "%{$data['realname']}%");
        }

        if ($data['collection_item']) {
            $map['dd.collection_item'] = array('=', "{$data['collection_item']}");
        }

        if ($data['collection_means']) {
            $map['dd.collection_means'] = array('=', "{$data['collection_means']}");
        }

        if ($data['collection_time']) {
            $map['dd.collection_time'] = array("between", [strtotime($data['collection_time'] . " 00:00:00"), strtotime($data['collection_time'] . " 23:59:59")]);
        }

        if ($data['refund_item']) {
            $map['dd.refund_item'] = array('=', "{$data['refund_item']}");
        }

        if ($data['refund_means']) {
            $map['dd.refund_means'] = array('=', "{$data['refund_means']}");
        }

        if ($data['refund_time']) {
            $map['dd.refund_time'] = array("between", [strtotime($data['refund_time'] . " 00:00:00"), strtotime($data['refund_time'] . " 23:59:59")]);
        }

        if ($data['driver_name'] === '新手') {
            $map['d.driver_rank_id'] = ['=', 0];
        } elseif ($data['driver_name'] === '初级' || $data['driver_name'] === '中级' || $data['driver_name'] === '高级') {
            $map['dr.name'] = array('=', "{$data['driver_name']}");
        }

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['dd.id'] = ['in', $id];
        }

        $list = Db::name('driver_deposit')
            ->alias('dd')
            ->join('tp_admin_user au', 'dd.driver_id=au.id', 'left')
            ->join('tp_driver d', 'dd.driver_id=d.user_id', 'left')
            ->join('tp_driver_rank dr', 'd.driver_rank_id=dr.id', 'left')
            ->where($map)
            ->field('dd.*,au.realname,d.driver_rank_id,dr.name')
            ->select();

        foreach ($list as $k => $v) {
            $list[$k]['driver_id'] = $list[$k]['realname'];
            $list[$k]['driver_rank_id'] = $list[$k]['name'];
            $list[$k]['collection_time'] = date("Y-m-d H:i:s", $list[$k]['collection_time']);
            $list[$k]['refund_time'] = date("Y-m-d H:i:s", $list[$k]['refund_time']);
            switch ($v['refund_status']) {
                case 4:
                    $list[$k]['refund_status'] = '审核中';
                    break;
                case 3:
                    $list[$k]['refund_status'] = '可退款';
                    break;
                case 2:
                    $list[$k]['refund_status'] = '部分项目退款';
                    break;
                case 1:
                    $list[$k]['refund_status'] = '全项目退款';
                    break;
                case 0:
                    $list[$k]['refund_status'] = '没有退款';
                    break;
            }
            unset($list[$k]['realname']);
            unset($list[$k]['name']);
        }
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "押金管理-押金管理数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 退款
     * @return mixed
     */
//    public function refund()
//    {
//        $data = input();
//        $map['id'] = $data['id'];
//        $user = Db::name("admin_user")->where('id', $data['id'])->find();
//        if (!$user['isdeposit']) {
//            return ajax_return_error('未交付');
//        }
//        $data['deposit_status'] = "refunded";
//        $data['isdeposit'] = false;
//        $data['deposit'] = 0;
//
//        unset($data['id']);
//        $re = Db::name("admin_user")->where($map)->update($data);
//        return ajax_return_adv('退款成功');
//
//    }

    /**
     * 申请退款
     * @return mixed
     */
    public function refund_apply()
    {
        $data = input();
        $map['id'] = $data['id'];
        $user = Db::name("admin_user")->where('id', $data['id'])->find();
        if (!$user['isdeposit']) {
            return ajax_return_error('未交付');
        }
        $data['deposit_status'] = "apply_refund";
        unset($data['id']);
        $re = Db::name("admin_user")->where($map)->update($data);
        return ajax_return_adv('正在申请');

    }

    /**
     * 提交押金
     * @return mixed
     */
    public function paid()
    {
        $data = input();
        $map['id'] = $data['id'];
        $user = Db::name("admin_user")->where('id', $data['id'])->find();
        $data['deposit_status'] = "paid";
        $data['isdeposit'] = true;

        set_info($data['id'], "已提交押金", "已提交押金");
        unset($data['id']);
        $re = Db::name("admin_user")->where($map)->update($data);
        return ajax_return_adv('提交成功');

    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $data = input();

        if ($this->request->isAjax()) {

            $flag = Db::name('driver_deposit')
                ->where('driver_id', $data['driver_id'])
                ->find();

            if ($flag) {
                return ajax_return_adv_error('该司机已交过押金!');
            }

            // 数组转字符串
            if (isset($data['collection_item']) && $data['collection_item'] != '' || $data['collection_item'] != null) {
                $data['collection_item'] = implode(',', $data['collection_item']);
            }

            $data['collection_time'] = time();

            $result = Db::name('driver_deposit')
                ->strict(false)
                ->insert($data);

            if ($result) {
                Db::name('admin_user')
                    ->where('id', $data['driver_id'])
                    ->update([
                        'deposit' => $data['collection_money'],
                        'deposit_status' => 'paid',
                        'isdeposit' => 1,
                        'deposit_time' => $data['collection_time'],
                    ]);
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }

        } else {
            // 返回司机列表
            $users = Db::name("admin_user")->select();
            $this->view->assign('users', $users);
            return $this->view->fetch();
        }
    }

    /**
     * 退款
     * @return mixed
     */
    public function refund()
    {
        $data = input();

        if ($this->request->isAjax()) {
            $driver_deposit = Db::name('driver_deposit')
                ->where('id',$data['id'])
                ->find();
            $flag = Db::name('admin_user')
                ->where('id',$driver_deposit['driver_id'])
                ->value('isdeposit');

            if (!$flag) {
                return ajax_return_adv_error('该司机没有交过押金!');
            }

            // 格式化时间
            if (isset($data['refund_time']) && $data['refund_time'] != '' || $data['refund_time'] != null) {
                $data['refund_time'] = strtotime($data['refund_time']);
            }else{
                return ajax_return_adv_error('请填写退款押金时间');
            }

            // 数组转字符串
            if (isset($data['refund_item']) && $data['refund_item'] != '' || $data['refund_item'] != null) {
                $data['refund_item'] = implode(',', $data['refund_item']);
            }

            $result = Db::name('driver_deposit')
                ->where('id',$data['id'])
                ->update([
                    'refund_item' => $data['refund_item'],
                    'refund_money' => $data['refund_money'],
                    'refund_means' => $data['refund_means'],
                    'refund_time' => $data['refund_time'],
                    'remark' => $data['remark']
                ]);

            if ($result) {

                $deposit = Db::name('driver_deposit')
                    ->where('id',$data['id'])
                    ->find();

                if ($data['refund_item'] === $deposit['collection_item']) {
                    $update = [
                        'deposit_status' => 'refunded',
                        'isdeposit' => 0
                    ];
                    Db::name('driver_deposit')
                        ->where('id',$data['id'])
                        ->setField('refund_status',1);
                } else {
                    $update = [
                        'deposit_status' => 'refunded',
                    ];
                    Db::name('driver_deposit')
                        ->where('id',$data['id'])
                        ->setField('refund_status',2);
                }
                Db::name('admin_user')
                    ->where('id', $driver_deposit['driver_id'])
                    ->update($update);
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }

        } else {

            // 返回押金信息
            $result = Db::name('driver_deposit')
                ->where('id', $data['id'])
                ->find();
            $this->view->assign('vo', $result);

            // 返回收款项目数组
            $refund_item = explode(',', $result['refund_item']);
            $this->view->assign('refund_item', $refund_item);

            return $this->view->fetch();
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $data = input();

        if ($this->request->isAjax()) {

            // 格式化时间
            if (isset($data['collection_time']) && $data['collection_time'] != '' || $data['collection_time'] != null) {
                $data['collection_time'] = strtotime($data['collection_time']);
            }

            // 数组转字符串
            if (isset($data['collection_item']) && $data['collection_item'] != '' || $data['collection_item'] != null) {
                $data['collection_item'] = implode(',', $data['collection_item']);
            }

            $result = Db::name('driver_deposit')
                ->where('id', $data['id'])
                ->strict(false)
                ->update($data);

            if ($result) {
                Db::name('admin_user')
                    ->where('id', $data['driver_id'])
                    ->update([
                        'deposit' => $data['collection_money'],
                        'deposit_time' => $data['collection_time']
                    ]);
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }

        } else {

            // 返回押金信息
            $result = Db::name('driver_deposit')
                ->where('id', $data['id'])
                ->find();
            $this->view->assign('vo', $result);

            // 返回收款项目数组
            $collection_item = explode(',', $result['collection_item']);
            $this->view->assign('collection_item', $collection_item);

            // 返回司机列表
            $users = Db::name("admin_user")->select();
            $this->view->assign('users', $users);

            // 返回司机ID
            $driver_id = $result['driver_id'];
            $this->view->assign('driver_id', $driver_id);

            return $this->view->fetch();
        }
    }

    /**司机详细资料**/
    public function details()
    {
        $data = input();

        $vo = Db::name('driver')->where('user_id', $data['id'])->find();
        if (!$vo) {
            return ajax_return_adv_error('不存在该司机信息');
        }
        $users = Db::name('admin_user')->where('id', $vo['user_id'])->find();
        if ($users['id']) {
            $users['user_id'] = $users['id'];
            unset($users['id']);
        }
        if (!$users) {
            return ajax_return_adv_error('不存在该司机的用户信息', 1);
        }
        //查询司机等级
        $driverRank = Db::name('driver_rank')->where('id', $vo['driver_rank_id'])->find();
        if ($driverRank) {
            $vo['driver_rank_id'] = $driverRank['name'];
        } else {
            $vo['driver_rank_id'] = '新手';
        }
        $this->view->assign('users', $users);
        $this->view->assign('vo', $vo);
        return $this->view->fetch('details');
    }
}